package handlers

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"swu.com/80p/internal/dbs"
)

// 获取表 Schema 的 Gin Handler
func GetSchemaHandler(c *gin.Context) {
	tableName := c.Param("tableName")
	if tableName == "" {
		c.JSON(http.StatusBadRequest, getGinError(errors.New("table name is required")))
		return
	}

	// GORM 没有直接获取原始 schema 的方法，但我们可以通过模型推断
	// 这里我们使用一个空模型，并指定表名
	var columns []ColumnInfo

	rows, err := dbs.GetDB().Table(tableName).Rows()
	if err != nil {
		c.JSON(http.StatusInternalServerError, getGinError(fmt.Errorf("error querying table: %v", err)))
		return
	}
	defer rows.Close()

	cols, _ := rows.Columns()
	columnTypes, _ := rows.ColumnTypes()

	for i, col := range cols {
		nullable, _ := columnTypes[i].Nullable()
		length, _ := columnTypes[i].Length()
		precision, scale, _ := columnTypes[i].DecimalSize()

		columnInfo := ColumnInfo{
			Name:      col,
			Type:      columnTypes[i].DatabaseTypeName(),
			Nullable:  nullable,
			Length:    length,
			Precision: precision,
			Scale:     scale,
		}
		columns = append(columns, columnInfo)
	}

	c.JSON(http.StatusOK, getGinResult(gin.H{"table": tableName, "columns": columns}))
}
